#!/usr/bin/python
# -*- coding: UTF-8 -*-
from selenium import webdriver;
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser=webdriver.Chrome()
from selenium.webdriver.common.keys import Keys
browser.set_window_size(1400,900)
wait=WebDriverWait(browser, 10)
from bs4 import BeautifulSoup
import re


def search():
    browser.get("https://weibo.com/")
    username = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#loginname"))
    )
    password = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".password .W_input"))
    )
    username.send_keys("18086107575")
    password.send_keys("441432")
    login = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#pl_login_form > div > div:nth-child(3) > div.info_list.login_btn > a')));
    login.click()

    search = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#plc_top > div > div > div.gn_search_v2 > input"))
    )
    search.send_keys("小猪佩奇")
    search.send_keys(Keys.ENTER)
    get_user()


def select_item(item,css,**kwargs):
    try:
        my=item.select(css)
        result=None
        if my == None:
          return None
        if len(my)==0:
            return None
        dest=my[0]
        if dest== None:
            return None
        if "text" in kwargs.keys():
            result= dest.get_text().strip()
        if "attrs" in kwargs.keys():
            result =dest.attrs[kwargs.get("attrs")]
        if "extract" in kwargs.keys():
            dest.extract()
    except Exception as e:
        print(e)
        result=None
    return result


def get_user():
    content = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#pl_weibo_direct"))
    )
    html = browser.page_source
    soup = BeautifulSoup(html, 'lxml')
    items=soup.select("#pl_weibo_direct .WB_feed_detail")
    for item in items:
        try:
            temp_url=select_item(item, ".feed_content a", attrs="href")
            user_name=select_item(item, ".feed_content a", attrs="nick-name")
            id= re.compile(r".*?u/(.*?)?refer_flag=1001030103_").search(temp_url).group(1)
            final_url = "https://weibo.com/p/{id}/info?mod=pedit_more"
            user_url=final_url.format(id=id)
        except:
            continue
        user={
            "user_name":user_name,
            "user_url":user_url
        }
        print(user)




def main():
    search()


if __name__ == '__main__':
    main()
